<script>
	import { routerGuard } from './common/router-guard.js'
	import { provide } from 'vue'
	import { useConfig } from '@/composables/useConfig.js'
	import { STORAGE_KEY } from '@/common/config.js'
	
	// 不需要登录的页面
	const publicPages = [
		'/pages/login/index',
		'/pages/login/register',
		'/pages/login/forgot',
		'/pages/common/agreement',
		'/pages/common/privacy'
	]
	
	export default {
		setup() {
			const config = useConfig()
			// 提供全局配置
			provide('config', config)
		},
		onLaunch: function() {
			console.log('App Launch')
			
			// 延迟执行路由检查，确保页面栈已经准备好
			setTimeout(() => {
				try {
					const userInfo = uni.getStorageSync(STORAGE_KEY.USER_INFO)
					const pages = getCurrentPages()
					
					if (pages && pages.length > 0) {
						const currentPage = pages[pages.length - 1]
						const currentPath = "/" + `${currentPage.route}`
						
						// 如果没有用户信息且不在公共页面，则跳转到登录页
						if (!userInfo && !publicPages.includes(currentPath)) {
							uni.redirectTo({
								url: '/pages/login/index'
							})
						}
					} else if (!userInfo) {
						// 如果获取不到页面栈且没有用户信息，直接跳转到登录页
						uni.redirectTo({
							url: '/pages/login/index'
						})
					}
				} catch (err) {
					console.error('路由检查失败:', err)
					// 发生错误时的默认处理
					uni.redirectTo({
						url: '/pages/login/index'
					})
				}
			}, 100)
		},
		onShow: function() {
			console.log('App Show')
			
			try {
				const userInfo = uni.getStorageSync(STORAGE_KEY.USER_INFO)
				const pages = getCurrentPages()
				
				if (pages && pages.length > 0) {
					const currentPage = pages[pages.length - 1]
					const currentPath = `/${currentPage.route}`
					
					if (!userInfo && !publicPages.includes(currentPath)) {
						uni.redirectTo({
							url: '/pages/login/index'
						})
					}
				}
			} catch (err) {
				console.error('登录状态检查失败:', err)
			}
		},
		onHide: function() {
			console.log('App Hide')
		},
		onPageNotFound: function() {
			uni.redirectTo({
				url: '/pages/login/index'
			})
		}
	}
</script>

<style lang="scss">
	/*每个页面公共css */
	@import './common/skeleton.scss';
</style>
